<template>
  <!-- 保持原有模板内容不变 -->
  <div class="select-page-demo">
    <h2 class="demo-title">Ant Design Vue SelectPage 示例</h2>

    <a-select
      v-model:value="selectedValues"
      :placeholder="selectedValues.length > 0 ? selectedItems.map(item => item.name).join(', ') : '请选择'"
      style="width: 100%"
      mode="multiple"
      :show-search="false"
      @popup-visible-change="handlePopupVisibleChange"
    >
      <!-- 自定义下拉内容 -->
      <template #dropdownRender="{ menuNode: menu }">
        <div class="custom-dropdown">
          <!-- 搜索框 -->
          <a-input
            v-model:value="searchQuery"
            placeholder="搜索选项..."
            allow-clear
            size="small"
            @input="handleSearch"
            class="search-input"
          />

          <!-- 加载状态 -->
          <a-spin :spinning="loading" v-if="loading" class="loading-spinner" />

          <!-- 表格展示选项 -->
          <a-table
            v-else-if="filteredItems.length > 0"
            :columns="columns"
            row-key="name"
            :data-source="filteredItems"
            :row-selection="rowSelection"
            :pagination="false"
            class="items-table"
          />

          <!-- 无结果提示 -->
          <div v-else class="no-result">
            没有找到匹配的选项
          </div>

          <!-- 分页控件 -->
          <a-pagination
            v-if="total > 0"
            :current="currentPage"
            :page-size="pageSize"
            :total="total"
            size="small"
            @change="handlePageChange"
            class="pagination"
          />
        </div>
      </template>
    </a-select>

    <!-- 选中结果展示 -->
    <a-card v-if="selectedItems.length > 0" class="result-card">
      <template #title>已选择信息</template>
      <div v-for="item in selectedItems" :key="item.id">
        <p>ID: {{ item.id }}</p>
        <p>名称: {{ item.name }}</p>
        <p>描述: {{ item.description }}</p>
        <hr />
      </div>
    </a-card>
  </div>
</template>

<script setup>
import { ref, computed, watch, h } from 'vue';
import { Select, Input, Table, Pagination, Card, Spin } from 'ant-design-vue';
import { UserOutlined } from '@ant-design/icons-vue';
import pinyin from 'pinyin';

// 状态管理
const selectedValues = ref([]);
const selectedItems = ref([]);
const searchQuery = ref('');
const currentPage = ref(1);
const pageSize = ref(5);
const total = ref(0);
const allItems = ref([]);
const loading = ref(false);

// 表格列配置
const columns = ref([
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
  },
  {
    title: '名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description',
  },
]);

// 计算当前页显示的选项
const filteredItems = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value;
  return allItems.value.slice(startIndex, startIndex + pageSize.value);
});

// 生成模拟数据，同时生成拼音
const generateMockData = (count) => {
  return Array.from({ length: count }, (_, i) => {
    const name = `选项 ${i + 1}`;
    const description = `这是选项 ${i + 1} 的详细描述信息，可包含更多内容用于展示`;
    return {
      id: i + 1,
      name,
      description,
      namePinyin: pinyin(name, { style: pinyin.STYLE_NORMAL }).flat().join(''),
      descriptionPinyin: pinyin(description, { style: pinyin.STYLE_NORMAL }).flat().join('')
    };
  });
};

// 加载数据
const loadData = async (query = '') => {
  loading.value = true;

  // 确保 query 是字符串类型
  const searchQueryStr = typeof query === 'string' ? query : String(query).toLowerCase();

  // 模拟 API 请求延迟
  await new Promise(resolve => setTimeout(resolve, 600));

  // 生成基础数据
  const baseData = generateMockData(50);

  // 根据搜索词过滤
  const filteredData = searchQueryStr
    ? baseData.filter(item => {
        const lowerSearchQuery = searchQueryStr.toLowerCase();
        return (
          item.name.toLowerCase().includes(lowerSearchQuery) ||
          item.description.toLowerCase().includes(lowerSearchQuery) ||
          item.namePinyin.includes(lowerSearchQuery) ||
          item.descriptionPinyin.includes(lowerSearchQuery)
        );
      })
    : baseData;

  allItems.value = filteredData;
  total.value = filteredData.length;
  loading.value = false;
};

// 处理搜索
const handleSearch = (value) => {
  currentPage.value = 1; // 重置到第一页
  loadData(value);
};

// 处理分页变化
const handlePageChange = (page) => {
  currentPage.value = page;
  // 滚动到列表顶部
  const listContainer = document.querySelector('.items-table');
  if (listContainer) listContainer.scrollTop = 0;
};

// 行选择配置，使用 computed 动态计算 selectedRowKeys
const rowSelection = computed(() => ({
  selectedRowKeys: selectedValues.value,
  onChange: (selectedRowKeys, selectedRows) => {
    selectedValues.value = selectedRowKeys;
    selectedItems.value = selectedRows;
  },
}));

// 处理下拉框显示/隐藏
const handlePopupVisibleChange = (visible) => {
  if (visible && allItems.value.length === 0) {
    loadData(); // 首次打开时加载数据
  }
};

// 监听选中值变化
watch(selectedValues, (value) => {
  if (value.length === 0) {
    selectedItems.value = [];
  }
});

// 初始化加载
loadData();
</script>

<style scoped>
/* 保持原有样式内容不变 */
.select-page-demo {
  max-width: 600px;
  margin: 2rem auto;
  padding: 0 1rem;
}

.demo-title {
  text-align: center;
  color: #1890ff;
  margin-bottom: 1.5rem;
}

.custom-dropdown {
  width: 100%;
  padding: 8px;
}

.search-input {
  margin-bottom: 12px;
  width: 100%;
}

.items-table {
  max-height: 240px;
  overflow-y: auto;
  margin-bottom: 8px;
}

.no-result {
  text-align: center;
  padding: 2rem 0;
  color: #666;
}

.loading-spinner {
  display: flex;
  justify-content: center;
  padding: 2rem 0;
}

.pagination {
  text-align: right;
}

.result-card {
  margin-top: 1rem;
}
</style>
